package com.liumuxian.exam.service.impl;

import com.liumuxian.exam.dao.ExamClassifyDao;
import com.liumuxian.exam.pojo.ExamClassify;
import com.liumuxian.exam.service.ExamClassifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import util.IdWorker;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional(readOnly = true)
public class ExamClassifyServiceImpl implements ExamClassifyService {
    @Autowired
    private ExamClassifyDao examClassifyDao;
    @Autowired
    private IdWorker idWorker;
    public List<ExamClassify> findAll(){
        return examClassifyDao.findAll();
    }
    @Override
    @Transactional
    public void save(ExamClassify examClassify){
        examClassify.setId(idWorker.nextId()+"");
        examClassify.setState(1);
        examClassify.setCreatedate(new Date());
        examClassifyDao.save(examClassify);
    }
    @Override
    @Transactional
    public void saveAll(List<ExamClassify> examClassify){
        examClassify.forEach(ec ->{
            ec.setId(idWorker.nextId()+"");
            ec.setState(1);
            ec.setCreatedate(new Date());
        });
        examClassifyDao.saveAll(examClassify);
    }
    @Override
    public void update(ExamClassify examClassify) {
        examClassifyDao.saveAndFlush(examClassify);
    }
    @Transactional
    @Override
    public void delete(String id) {
        ExamClassify examClassify = examClassifyDao.findById(id).get();
        examClassify.setState(0);
        examClassifyDao.saveAndFlush(examClassify);
    }
    @Override
    public ExamClassify findById(String id) {
        return examClassifyDao.findById(id).get();
    }

    @Override
    public List<ExamClassify> findAllGesTate(String id, String name, Integer state) {
        return examClassifyDao.findAll((Root<ExamClassify> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) -> {
            List<Predicate> predicateList = new ArrayList<Predicate>();
            if (id != null && !StringUtils.isEmpty(id)) {
                predicateList.add(criteriaBuilder.equal(root.get("id"), id));
            }
            if (name != null && !StringUtils.isEmpty(name)) {
                predicateList.add(criteriaBuilder.like(root.get("name"), "%" + name + "%"));
            }
            if (state != null && !StringUtils.isEmpty(state)) {
                predicateList.add(criteriaBuilder.ge(root.get("state"), (Number) state));
            }
            return criteriaBuilder.and( predicateList.toArray(new Predicate[predicateList.size()]));
        });
    }

}
